/*
Problem: Add Two Number
Difficulty: easy
Source:  http://www.leetcode.com/onlinejudge
Notes:
You are given two linked lists representing two non-negative
numbers. The digits are stored in reverse order and each of
their nodes contain a single digit. Add the two numbers and
return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/

#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
  ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  	if (l1 == NULL || l2 == NULL)
  		return NULL;

  	ListNode* result = NULL;
  	ListNode* tail = result;
  	int sum = 0, carry = 0;
  	int a, b;
  	while (l1 || l2) {
  		if (l1) a = l1->val; else a = 0;
  		if (l2) b = l2->val; else b = 0;
  		sum = a + b + carry;
  		carry = sum % 10;
  		sum /= 10;
  		ListNode* node = new ListNode(sum);
  		if (result == NULL) {
  			result = tail = node;
  		} else {
  			tail->next = node;
  			tail = node;
  		}
  		l1 = l1->next;
  		l2 = l2->next;
  	}

  	if (carry) {
  		ListNode* node = new ListNode(carry);
  		tail->next = node;
  	}
  	return result;
  }
};

int main(int argc, char* argv[])
{
	Solution s;
	ListNode* l1 = new ListNode(9);
	ListNode* l2 = new ListNode(9);
	ListNode* result = s.addTwoNumbers(l1, l2);
	ListNode* p = result;
	while (p) {
		cout << p->val;
		p = p->next;
	}
	cout << endl;
	return 0;
}